package com.yzy.util.oss;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.yzy.exception.VisionException;
import com.yzy.properties.GlobalProperties;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.*;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: minio工具类
 * 
 * @Date: 2022/8/17
 **/
@Component
public class MinioUtil {

    @Resource
    private GlobalProperties globalProperties;

    private static MinioClient minioClient;

    @PostConstruct
    public void init() {
        try {
            minioClient = new MinioClient(globalProperties.getEndpoint(), globalProperties.getAccessKey(),
                    globalProperties.getSecretKey());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static MinioClient getMinioClient() {
        return minioClient;
    }

    /**
     * 检查存储桶是否存在
     *
     * @param bucketName 存储桶名称
     * @return
     */
    public boolean bucketExists(String bucketName) {
        boolean flag = false;
        try {
            flag = minioClient.bucketExists(bucketName);
            if (flag) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 创建存储桶
     *
     * @param bucketName 存储桶名称
     */
    public boolean makeBucket(String bucketName) {
        try {
            boolean flag = bucketExists(bucketName);
            //存储桶不存在则创建存储桶
            if (!flag) {
                minioClient.makeBucket(bucketName);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 上传文件
     *
     * @param file 上传文件
     * @return 成功则返回文件名，失败返回空
     */
    private String uploadFile(MultipartFile file) {
        //创建存储桶
        boolean createFlag = makeBucket(globalProperties.getBucketName());
        //创建存储桶失败
        if (!createFlag) {
            return "";
        }
        try {
            PutObjectOptions putObjectOptions = new PutObjectOptions(file.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
            putObjectOptions.setContentType(file.getContentType());
            String originalFilename = file.getOriginalFilename();
            int pointIndex = originalFilename.lastIndexOf(".");
            //得到文件流
            InputStream inputStream = file.getInputStream();
            //保证文件不重名(并且没有特殊字符)
            String fileName = globalProperties.getBucketName() + DateUtil.format(new Date(), "_yyyyMMddHHmmssSSS") + (pointIndex > -1 ? originalFilename.substring(pointIndex) : "");
            minioClient.putObject(globalProperties.getBucketName(), fileName, inputStream, putObjectOptions);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public String updateFileGetUrl(MultipartFile file) {
        try {
//            if (file.getSize() > 2000 * 1024) {
//                throw new VisionException(HttpStatus.FORBIDDEN, "文件大小不能超过2m！！！");
//            }
            return minioClient.presignedGetObject(globalProperties.getBucketName(), uploadFile(file));
        } catch (IOException | InvalidBucketNameException | ErrorResponseException | InvalidExpiresRangeException | InvalidKeyException | InvalidResponseException | XmlParserException | NoSuchAlgorithmException | InsufficientDataException | InternalException e) {
            e.printStackTrace();
            return null;
        }
    }

    public List<String> updateFileGetUrls(MultipartFile[] files) {
        List<String> list = new ArrayList<>();
        for (MultipartFile file : files) {
            try {
                if (file.getSize() > 2000 * 1024) {
                    throw new VisionException(HttpStatus.FORBIDDEN, "文件大小不能超过2m！！！");
                }
                list.add(minioClient.presignedGetObject(globalProperties.getBucketName(), uploadFile(file)));
            } catch (IOException | InvalidBucketNameException | ErrorResponseException | InvalidExpiresRangeException | InvalidKeyException | InvalidResponseException | XmlParserException | NoSuchAlgorithmException | InsufficientDataException | InternalException e) {
                e.printStackTrace();
                return null;
            }
        }
        return list;
    }

    public String updateFileGetFileName(MultipartFile file) {
        return uploadFile(file);
    }

    /**
     * 下载文件
     *
     * @param originalName 文件路径
     */
    public InputStream downloadFile(String originalName, HttpServletResponse response) {
        try {
            InputStream inputStream = minioClient.getObject(globalProperties.getBucketName(), originalName);
            String filename = new String(originalName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
            if (StrUtil.isNotBlank(originalName)) {
                filename = originalName;
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");

            /*response.setHeader("Content-Disposition", "attachment;filename=" + filename);*/

            ServletOutputStream servletOutputStream = response.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer)) > 0) {
                servletOutputStream.write(buffer, 0, len);
            }
            servletOutputStream.flush();
            inputStream.close();
            servletOutputStream.close();
            return inputStream;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 删除文件
     *
     * @param fileName 文件路径
     * @return
     */
    public boolean deleteFile(String fileName) {
        try {
            minioClient.removeObject(globalProperties.getBucketName(), fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 得到指定文件的InputStream
     *
     * @param originalName 文件路径
     * @return
     */
    public InputStream getObject(String originalName) {
        try {
            return minioClient.getObject(globalProperties.getBucketName(), originalName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据文件路径得到预览文件绝对地址
     *
     * @param fileName 文件路径
     * @return
     */
    public String getPreviewFileUrl(String fileName) {
        try {
            return minioClient.presignedGetObject(globalProperties.getBucketName(), fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 文件上传：文件名不变更，便于下载
     *
     * @param file：上传文件名
     * @author： wyx
     */
    @SneakyThrows(Exception.class)
    public void uploadFile2(MultipartFile file) {
        String bucketName = globalProperties.getBucketName();
        //如果存储桶不存在则创建
        if (!bucketExists(bucketName)) {
            makeBucket(bucketName);
        }
        PutObjectOptions putObjectOptions = new PutObjectOptions(file.getInputStream().available(), -1);
        putObjectOptions.setContentType(file.getContentType());

        String originalFilename = file.getOriginalFilename();
        //得到文件流
        InputStream inputStream = file.getInputStream();

        minioClient.putObject(bucketName, originalFilename, inputStream, putObjectOptions);
    }

    /**
     * 文件在线阅读
     *
     * @param bucketName：桶名
     * @param fileName：阅读文件名
     * @return 文件内容
     * @author： wyx
     */
    @SneakyThrows(Exception.class)
    public String viewOnline(String bucketName, String fileName) {
        StringBuilder content = new StringBuilder();

        InputStream is = minioClient.getObject(bucketName, fileName);
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        // 读取文件
        String thisLine;
        while ((thisLine = in.readLine()) != null) {
            content.append(thisLine);
        }

        return content.toString();
    }

}
